<script setup>
import { ref, defineProps, defineEmits, computed, watchEffect } from 'vue';
import DOMPurify from 'dompurify';
import LikeButton from '../Forum/LikeButton.vue';
import CommentSection from '../Comment/CommentSection.vue';
import { postService } from "@/services/PostService.js";
import { userManager } from "@/utils/user.js";
import { userServie } from "@/services/user_service.js";
import { ElMessage, ElCard, ElButton } from 'element-plus';

const props = defineProps({
  post: { type: Object, required: true },
});
defineEmits(['toggleLike']);

const showComments = ref(false);
const isLoadingComments = ref(false);
const comments = ref([]);
const username = ref('');

watchEffect(async () => {
  if (props.post && props.post.author) {
    try {
      const user = await userServie.getUserById(props.post.author);
      username.value = user.username || '未知作者';
    } catch (error) {
      console.error("获取作者用户名失败:", error);
      username.value = '未知作者';
    }
  }
});

const sanitizedContent = computed(() => {
  return props.post.content ? DOMPurify.sanitize(props.post.content) : '';
});

const fetchCommentsForThisPost = async () => {
  isLoadingComments.value = true;
  try {
    comments.value = await postService.getCommentsByPostId(props.post.id);
  } catch (error) {
    console.error(`获取帖子 ${props.post.id} 的评论失败:`, error);
  } finally {
    isLoadingComments.value = false;
  }
};

const toggleComments = async () => {
  showComments.value = !showComments.value;
  if (showComments.value && comments.value.length === 0) {
    await fetchCommentsForThisPost();
  }
};

const handleAddNewComment = async (commentContent) => {
  try {
    await postService.createComment({
      contenter: userManager.getUserId(),
      postId: props.post.id,
      content: commentContent,
    });
    ElMessage.success("评论发表成功！");
    if (props.post.commentCount !== undefined) {
      props.post.commentCount++;
    }
    await fetchCommentsForThisPost();
  } catch (error) {
    console.error('发表评论失败:', error);
    ElMessage.error('评论失败，请重试。');
  }
};

const formatDate = (dateValue) => {
  if (!dateValue) return '日期未知';
  const date = new Date(dateValue);
  return isNaN(date.getTime()) ? '无效日期' : date.toLocaleDateString();
};
</script>

<template>
  <el-card shadow="never" class="post-card">
    <h3 class="post-title">{{ post.title }}</h3>
    <p class="post-meta">
      <strong>{{ username }}</strong>
      <span>发布于 {{ formatDate(post.createTime) }}</span>
    </p>

    <div class="post-content" v-html="sanitizedContent"></div>

    <div class="post-actions">
      <LikeButton
          :likes="post.likes"
          :is-liked="post.liked === 'true'"
          @toggle-like="$emit('toggleLike', post.id)"
      />
      <el-button link type="primary" @click="toggleComments" :loading="isLoadingComments">
        {{ showComments ? '收起评论' : `查看 ${post.commentCount || 0} 条评论` }}
      </el-button>
    </div>

    <CommentSection
        v-if="showComments"
        :comments="comments"
        @add-comment="handleAddNewComment"
    />
  </el-card>
</template>

<style scoped>
.post-card {
  border-radius: 12px;
  border: 1px solid #e0e0e0;
}
.post-title {
  font-size: 18px;
  font-weight: 600;
  color: #202124;
  margin: 0 0 8px 0;
}
.post-meta {
  font-size: 13px;
  color: #5f6368;
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 16px;
}
.post-content {
  color: #3c4043;
  line-height: 1.7;
  font-size: 15px;
  margin-bottom: 20px;
  white-space: pre-wrap;
}
.post-actions {
  display: flex;
  gap: 16px;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}
</style>